package net.towee.server.xmpp;

import javax.inject.Inject;

import net.towee.model.account.AccountData;
import net.towee.model.utils.Pair;
import net.towee.server.authentication.PasswordDigest;
import net.towee.server.persistence.AccountStore;
import net.towee.shared.exceptions.PersistenceException;

import org.apache.vysper.xmpp.addressing.Entity;
import org.apache.vysper.xmpp.authentication.AccountCreationException;
import org.apache.vysper.xmpp.authentication.AccountManagement;
import org.apache.vysper.xmpp.authentication.UserAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Account manager for xmpp server
 * 
 * @author c58
 */
public class XmppAccountManager implements UserAuthentication, AccountManagement {
	private static final Logger LOG = LoggerFactory.getLogger(XmppAccountManager.class);
	private final AccountStore accountManager;

	@Inject
	public XmppAccountManager(AccountStore accountManager) {
		this.accountManager = accountManager;
	}
	
	@Override
	public void addUser(Entity username, String password) throws AccountCreationException {
		// not supported
	}

	@Override
	public void changePassword(Entity username, String password) throws AccountCreationException {
		// not supported
	}

	@Override
	public boolean verifyAccountExists(Entity jid) {
		LOG.info("Try to verify account exists "+jid.getNode());
		
		return accountManager.checkAccountWithNickName( jid.getNode() );
	}

	@Override
	public boolean verifyCredentials(Entity jid, String passwordCleartext, Object credentials) {
		LOG.info("Verifying account by JID"+jid.getFullQualifiedName());
		
		try {
			AccountData acc = accountManager.getAccountByNickname(jid.getNode(), "salt", "digest");
			Pair<byte[], byte[]> sd = acc.getSaltDigest();
			PasswordDigest digest = new PasswordDigest(sd.getFirst(), sd.getSecond());
			
			return digest.verify( passwordCleartext.toCharArray() );
		} catch (PersistenceException e) {
			return false;
		}
	}

}
